package com.hk.commons.jackson;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import com.hk.commons.jackson.annotations.EnumField;

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Objects;

public class EnumSerializer extends StdSerializer<Object> {

    private final EnumField enumField;

    protected EnumSerializer(EnumField enumField) {
        super(Object.class);
        this.enumField = enumField;
    }

    @Override
    public Class<Object> handledType() {
        return Object.class;
    }

    @Override
    public void serialize(Object value, JsonGenerator gen, SerializerProvider provider) throws IOException {
        gen.writeObject(value);
        try {
            Enum<?>[] enumConstants = enumField.target().getEnumConstants();
            Field valueField = enumField.target().getDeclaredField(enumField.valueField());
            Field labelField = enumField.target().getDeclaredField(enumField.labelField());
            valueField.setAccessible(true);
            labelField.setAccessible(true);
            for (Enum<?> enumConstant : enumConstants) {
                Object label = valueField.get(enumConstant);
                if (Objects.equals(label, value)) {
                    gen.writeObjectField(gen.getOutputContext().getCurrentName().concat("Name"), labelField.get(enumConstant));
                    break;
                }
            }
        } catch (Exception e) {
            // ignore
        }
    }
}
